//
//  ShopBagViewController.m
//  ChunLaiZhuangClient
//
//  Created by zouzhisheng on 16/2/15.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "ShopBagViewController.h"
#import "ShopBagTableViewCell.h"
#import "SettlementViewController.h"
#import "CartListModel.h"
#import "ShopBagTableViewFootCell.h"
#import "LoginViewController.h"
#import "AppContext.h"
#import "CLZRefreshHeader.h"
#import "ShopBagEmptyView.h"
#import "ProductInfoViewController1.h"
#import "LocalStateManager.h"
static BOOL SELECT_ALL_COMMODITY = NO;
@interface ShopBagViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, SettleupCommodityDelegate>

@property(nonatomic, strong) UINavigationController *settlementNavi;
@property(nonatomic, strong) SettlementViewController *settlementVC;
@property(nonatomic, strong) NSMutableArray *commodityArray;
@property(nonatomic, strong) CartProductModel *deletingCommodity;
@property(nonatomic, strong) UIView *headView;
@property(nonatomic, strong) UIButton *selectAllBtn;
@property (strong, nonatomic) UIButton *settlementBtn;
@property(nonatomic, strong) UIView *footView;
@property(nonatomic, strong) ShopBagEmptyView *emptyView;
@property(nonatomic, strong) NSArray *totalArray;
@property(nonatomic, strong) UIView *backView;
@end

@implementation ShopBagViewController

- (void)loadView {
    [super loadView];
    self.headView = [[[NSBundle mainBundle] loadNibNamed:@"ShopBagViewController" owner:self options:nil] objectAtIndex:1];
    self.selectAllBtn = [[self.headView subviews] objectAtIndex:1];
}

- (void)setEnableBack:(BOOL)enableBack {
    _enableBack = enableBack;
    if (_enableBack) {
        [self setNaviLeftButton];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.selected=YES;
    UILabel *titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, 100, 30)];
    titleLabel.text=@"    购物袋";
    titleLabel.font=[UIFont boldSystemFontOfSize:18];
    self.navigationItem.titleView=titleLabel;
    [self setNaviRightButton:@"编辑" action:YES];
    self.shopBagTableView.delegate = self;
    self.shopBagTableView.dataSource = self;
    self.shopBagTableView.hidden = YES;
    self.emptyView.hidden = YES;
    self.backView.alpha = 0.f;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editAction:) name:@"DonotdisturbViewController" object:nil];
    __weak typeof(self) weakSelf = self;
    self.shopBagTableView.mj_header = [CLZRefreshHeader headerWithRefreshingBlock:^{
        [weakSelf getCartList];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    RIGHTNAVIGUTTON_IS_EDITING = NO;
    [self setNaviRightButton:@"编辑"];
    [self getCartList];
}

- (ShopBagEmptyView *)emptyView {
    if (!_emptyView) {
        _emptyView = [[ShopBagEmptyView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:_emptyView];
        [_emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.trailing.leading.equalTo(@(0));
        }];
    }
    return _emptyView;
}

- (UIView *)backView {
    if (!_backView) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f];
        [self.navigationController.view addSubview:_backView];
    }
    return _backView;
}

- (void)getCartList {
    [ApiClient getCardListDidfinishLoaded:^(CartListModel *model, NSString *path) {
        [self.shopBagTableView.mj_header endRefreshing];
        if ([model.status isEqual:@(1)]) {
            self.commodityArray = [NSMutableArray arrayWithArray:model.data.products];
            self.totalArray = model.data.totals;
            if (self.commodityArray.count > 0) {
                self.shopBagTableView.hidden = NO;
                self.emptyView.hidden = YES;
                [self setNaviRightButton:@"编辑"];
            } else {
                self.emptyView.hidden = NO;
                [self setNaviRightButton:nil];
                self.shopBagTableView.hidden = YES;
            }
            [self.shopBagTableView reloadData];
            BOOL selectAll = YES;
            for(CartProductModel *product in self.commodityArray) {
                if (!product.checked) {
                    selectAll = NO;
                    break;
                }
            }
            SELECT_ALL_COMMODITY = selectAll;
            [self setSelectAllBtnBackImage];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        [self.shopBagTableView.mj_header endRefreshing];
        self.shopBagTableView.hidden = YES;
    }];
}

- (UINavigationController *)settlementNavi {
    if(!_settlementNavi) {
        _settlementNavi = [[UINavigationController alloc] initWithRootViewController:self.settlementVC];
        _settlementNavi.view.frame = self.view.frame;
    }
    return _settlementNavi;
}

- (SettlementViewController *)settlementVC {
    if (!_settlementVC) {
        CartTotalModel *tranceTotal = [self.totalArray objectAtIndex:1];
        CartTotalModel *priceTotal = [self.totalArray objectAtIndex:2];        
        _settlementVC = [[SettlementViewController alloc] initWithTransPrice:tranceTotal.text andTotalPrice:priceTotal.text];
        _settlementVC.delegate = self;
        _settlementVC.view.backgroundColor = [UIColor clearColor];
        _settlementVC.view.frame = self.view.frame;
        _settlementVC.view.height = self.view.height - 100.f;
    }
    return _settlementVC;
}

- (UIView *)footView {
    if (!_footView) {
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 90.f)];
        [_footView addSubview:self.settlementBtn];
    }
    return _footView;
}

- (UIButton *)settlementBtn {
    if (!_settlementBtn) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _settlementBtn = [[UIButton alloc] initWithFrame:CGRectMake(14.f, 20.f, width - 28.f, 50.f)];
        _settlementBtn.layer.cornerRadius = 24.f;
        [_settlementBtn setTitle:@"结算" forState:UIControlStateNormal];
        [_settlementBtn setBackgroundColor:[UIColor colorWithRGB:0xf35959]];
        _settlementBtn.titleLabel.font = [UIFont boldSystemFontOfSize:22.f];
        [_settlementBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_settlementBtn addTarget:self action:@selector(settleUpAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _settlementBtn;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *tCell;
    if (indexPath.row < self.commodityArray.count) {
        static NSString *identifier = @"ShopBagCell";
        tCell = [tableView dequeueReusableCellWithIdentifier:
                                      identifier];
        if (!tCell) {
            tCell = [[[NSBundle mainBundle] loadNibNamed:@"ShopBagTableViewCell" owner:self options:nil] lastObject];
        }
        ShopBagTableViewCell *cell = (ShopBagTableViewCell *)tCell;
        [cell updateWithProductModel:[self.commodityArray objectAtIndex:indexPath.row] isEditing:RIGHTNAVIGUTTON_IS_EDITING];
        cell.selectCommodityBlock = ^(CartProductModel *product){
            if (!product.checked) {
                [ApiClient unSelectProductToPay:product.cart_id didFinishLoaded:^(KXJson *json, NSString *path) {
                    if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                        SELECT_ALL_COMMODITY = NO;
                        [self setSelectAllBtnBackImage];
                        [self getCartList];
                    } else {
                        product.checked = YES;
                    }
                } didFailLoaded:^(NSError *error, NSString *path) {
                    product.checked = YES;
                }];
            } else {
                [ApiClient selectProductToPay:product.cart_id didFinishLoaded:^(KXJson *json, NSString *path) {
                    if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                        BOOL selectAll = YES;
                        for(CartProductModel *product in self.commodityArray) {
                            if (!product.checked) {
                                selectAll = NO;
                                break;
                            }
                        }
                        SELECT_ALL_COMMODITY = selectAll;
                        [self setSelectAllBtnBackImage];
                        [self getCartList];
                    } else {
                        product.checked = NO;
                    }
                } didFailLoaded:^(NSError *error, NSString *path) {
                    product.checked = NO;
                }];
                
            }
        };
        __weak typeof(cell) weakCell = cell;
        cell.updateProductQuantity = ^(CartProductModel *product, NSInteger quantity) {
            [ApiClient updateProductQuantityInCart:product.cart_id quantity:quantity didFinishLoaded:^(KXJson *json, NSString *path) {
                if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                    [weakCell updateProductQuantityInfo:quantity];
                    [self getCartList];
                }
            } didFailLoaded:^(NSError *error, NSString *path) {
            }];
        };
        cell.deleteProductAction = ^(CartProductModel *product) {
            self.deletingCommodity = product;
            [self deleteCommodityAction:nil];
        };
    } else {
        static NSString *identifier = @"ShopBagFootCell";
        tCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!tCell) {
            tCell = [[[NSBundle mainBundle] loadNibNamed:@"ShopBagTableViewFootCell" owner:self options:nil] lastObject];
        }
        ShopBagTableViewFootCell *cell = (ShopBagTableViewFootCell *)tCell;
        [cell updateWithSettleInfo:self.totalArray];
    }
   
    tCell.selectionStyle = UITableViewCellSelectionStyleNone;
    return tCell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commodityArray.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row < self.commodityArray.count) {
        return 105.f;
    } else {
        ShopBagTableViewFootCell *cell = (ShopBagTableViewFootCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        return [cell heightForRow];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 90.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return self.footView;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.headView;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.commodityArray.count) {
        CartProductModel *model = [self.commodityArray objectAtIndex:indexPath.row];
        ProductInfoViewController1 *productVC = [[ProductInfoViewController1 alloc] initWithProductId:[NSString stringWithFormat:@"%@", model.product_id]];
        [self.navigationController pushViewController:productVC animated:YES];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.commodityArray.count) {
        return YES;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        self.deletingCommodity = [self.commodityArray objectAtIndex:indexPath.row];
        [self deleteCommodityAction:nil];
    }
}

- (void)editAction:(id)sender {
    RIGHTNAVIGUTTON_IS_EDITING = !RIGHTNAVIGUTTON_IS_EDITING;
    if (RIGHTNAVIGUTTON_IS_EDITING) {
        [self setNaviRightButton:@"完成"];
    } else {
        [self setNaviRightButton:@"编辑"];
    }
}

#pragma --mark deleteCommodity
- (void)deleteCommodityAction:(id)sender {
    if (self.deletingCommodity) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确定要删除吗？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSInteger index = [self.commodityArray indexOfObject:self.deletingCommodity];
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
        [self deleteCommodity:nil atIndexPath:indexPath];
    }
}

- (void)deleteCommodity:(id)sender atIndexPath:(NSIndexPath *)indexPath {
    CartProductModel *model = [self.commodityArray objectAtIndex:indexPath.row];
    [ApiClient deleteProductIncard:model.cart_id didFinishLoaded:^(KXJson *json, NSString *path) {
        if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
            [self.commodityArray removeObjectAtIndex:indexPath.row];
            [self.shopBagTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
            if (self.commodityArray.count <= 0) {
                self.shopBagTableView.hidden = YES;
                self.emptyView.hidden = NO;
                [self setNaviRightButton:nil];
            }
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
}

#pragma --mark select all commodity

- (IBAction)selectAllAction:(id)sender {
    SELECT_ALL_COMMODITY = !SELECT_ALL_COMMODITY;
    if (SELECT_ALL_COMMODITY) {
        [ApiClient selectAllProductToCart:^(KXJson *json, NSString *path) {
            if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                [self setSelectAllBtnBackImage];
                for (CartProductModel *model in self.commodityArray) {
                    model.checked = SELECT_ALL_COMMODITY;
                }
                [self getCartList];
            } else {
                SELECT_ALL_COMMODITY = !SELECT_ALL_COMMODITY;
            }
        } didFailLoaded:^(NSError *error, NSString *path) {
            SELECT_ALL_COMMODITY = !SELECT_ALL_COMMODITY;
        }];
    } else {
        [ApiClient unSelectAllProductToCart:^(KXJson *json, NSString *path) {
            if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                [self setSelectAllBtnBackImage];
                for (CartProductModel *model in self.commodityArray) {
                    model.checked = SELECT_ALL_COMMODITY;
                }
                [self getCartList];
            } else {
                SELECT_ALL_COMMODITY = !SELECT_ALL_COMMODITY;
            }
        } didFailLoaded:^(NSError *error, NSString *path) {
            SELECT_ALL_COMMODITY = !SELECT_ALL_COMMODITY;
        }];
    }

}

- (void)setSelectAllBtnBackImage {
    if (SELECT_ALL_COMMODITY) {
        [self.selectAllBtn setImage:[UIImage imageNamed:@"btn_select_selectd"] forState:UIControlStateNormal];
    } else {
        [self.selectAllBtn setImage:[UIImage imageNamed:@"btn_select_nor"] forState:UIControlStateNormal];
    }
}

- (void)settleUpAction:(id)sender {
    if (![LocalStateManager shareLocalStateManager].selected) {
       [[LKDHud shareHud] showtip:@"请阅读个人委托协议并确认"];
        return;
    }
    BOOL selectProduct = NO;
    for (CartProductModel *product in self.commodityArray) {
        if (product.checked) {
            selectProduct = YES;
        }
    }
    if (!selectProduct) {
        [[LKDHud shareHud] showtip:@"请先选中购物车中的任意商品再进行结算"];
        return;
    }
    
    if (!APP_CONTEXT.account) {
        [LoginViewController presentLoginViewController:self withCompleteBlock:nil];
        return;
    }
    self.backView.alpha = 1.f;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        self.settlementNavi.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }else{
        self.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;
    [controller presentViewController:self.settlementNavi animated:YES completion:^{
        [self.settlementVC getCheckoutInfos];
    }];
}

#pragma SettlementViewControllerDelegate

- (void)closeSettlementViewController:(SettlementViewController *)settleVC {
    self.backView.alpha = 0.f;
    [self.settlementVC dismissViewControllerAnimated:YES completion:^{
        self.settlementVC = nil;
        self.settlementNavi = nil;
    }];
}

- (void)showReceiptAddressAction:(SettlementViewController *)settleVC {
    
}

- (void)payEndAction:(SettlementViewController *)settleVC {
    self.backView.alpha = 0.f;
    [self.settlementVC dismissViewControllerAnimated:YES completion:^{
        self.settlementVC = nil;
        self.settlementNavi = nil;
        [self getCartList];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
